package com.taotao.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.taotao.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.taotao.common.pojo.BaseResult;
import com.taotao.common.utils.RedisUtils;
import com.taotao.controller.ApiSocketController;
import com.taotao.mapperCust.CommonMapperCust;
import com.taotao.mapperCust.EyChatMapperCust;
import com.taotao.pojo.EyCategory;
import com.taotao.pojo.EyCategoryExample;
import com.taotao.pojo.EyGoods;
import com.taotao.pojo.EyMember;
import com.taotao.pojo.EyMessageInfo;
import com.taotao.pojo.EyMessageInfoExample;
import com.taotao.pojo.EyRobotChat;
import com.taotao.pojo.EyRobotChatExample;
import com.taotao.service.ParamService;

/**
 * 机器人发送消息
 */
@Controller
public class RobotMsgTask {
	
	@Autowired
	ApiSocketController apiSocketController;
	@Autowired
	ParamService paramService;
	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	CommonMapperCust commonMapperCust;
	@Autowired
	EySessionInfoMapper eySessionInfoMapper;
	@Autowired
	EyMessageInfoMapper eyMessageInfoMapper;
	@Autowired
	EyMemberMapper eyMemberMapper;
	@Autowired
	EyRobotChatMapper eyRobotChatMapper;
	@Autowired
	EyCategoryMapper eyCategoryMapper;
	@Autowired
	EyChatMapperCust eyChatMapperCust;
	BaseResult baseResult = new BaseResult();
	
	
//    @Scheduled(cron = "0 */15 8-23 * * ? ") // 间隔10分钟执行
	@RequestMapping("/api/robotMsgFirst")
	@ResponseBody
    public  Map<String, Object>  robotMsgFirst() {
		Integer count=0;
    	try {
    		boolean lock = RedisUtils.tryGetDistributedLock("lockKey_robotMsg", "robotMsg", 60000);
			if(lock){
				String param = paramService.getParam("job_RobotMsgTaskTask");
	    		if("true".equals(param)){
	    			System.out.println("robotMsgFirst执行开始...");
	    			//获取开头聊天话术
	    			EyRobotChatExample exampleChat = new EyRobotChatExample();
					com.taotao.pojo.EyRobotChatExample.Criteria criteriaChat = exampleChat.createCriteria();
					criteriaChat.andTypeEqualTo("1");
					List<EyRobotChat> chatList = eyRobotChatMapper.selectByExample(exampleChat);
					
					//获取分类 查二手和房源的分类
					List<Integer> parantList=new ArrayList<Integer>();
					parantList.add(1); //二手 大类
//					parantList.add(3);//房产大类
					EyCategoryExample exampleCate= new EyCategoryExample();
					com.taotao.pojo.EyCategoryExample.Criteria criteriaCate = exampleCate.createCriteria();
					criteriaCate.andParentIdIn(parantList);
					List<EyCategory> categoryList = eyCategoryMapper.selectByExample(exampleCate);
					
					StringBuffer s = new StringBuffer(); 
					s.append("(");
					for (EyCategory c:categoryList) {
						s.append("'").append(c.getId()).append("'").append(","); 
					}
		    		s.deleteCharAt(s.length() - 1);
		    		s.append(")");
		    		String catetoryIds=s.toString();
		    		
		    		Calendar calendar1 = Calendar.getInstance();
		    		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
		    		calendar1.add(Calendar.DATE, -3);
		    		String createTime = sdf1.format(calendar1.getTime());
					
					String  executeSql="SELECT	*  FROM "
							+ "	ey_goods WHERE 1=1"
							+ "	and member_id IN "
							+ " (SELECT id FROM ey_member WHERE	source_id IS NULL AND id NOT IN "
							+ "		( SELECT member_id FROM ey_operate_log "
							+ "			WHERE create_time > '${createTime}' "
							+ "			 AND operate_type = '${operateType}' GROUP BY member_id "
							+ "		) "
							+ "	) "
							+ " and category_id in ${catetoryIds} "
							+ " and status ='1' "
							+ " ORDER BY rand()	LIMIT 5";
					
					executeSql=executeSql.replace("${catetoryIds}", catetoryIds);
					executeSql=executeSql.replace("${createTime}",createTime);
					executeSql=executeSql.replace("${operateType}", "20"); //登录过
					List<Map> executeGoodsMap = commonMapperCust.executeSql(executeSql);
					
					HashMap<String,String> existMemberMap=new HashMap<String,String>();
					for(Map map:executeGoodsMap){
						String goodsId=String.valueOf(map.get("id"));
						String memberId = String.valueOf(map.get("member_id"));
						if(existMemberMap.get(memberId)!=null){
							continue;
						}
						
						EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
						
						String nickName=member.getNickName();
						if(nickName.indexOf("'")!=-1){
							 nickName=nickName.replace("'", "");
					    }
					
						executeSql="select * from ey_member where 1=1"
								+ "	and source_id is not null "
								+ " and id not in "
								+ " (select sender from ey_session_info  where goods_id ='${goodsId}'  )"
//								+ " and nick_name not like '%${nickName}%' "
								+ "order by rand() limit 1 ";
						
						executeSql=executeSql.replace("${goodsId}", goodsId);
//						executeSql=executeSql.replace("${nickName}", member.getNickName());
						List<Map> executeMemberMap = commonMapperCust.executeSql(executeSql);
						Map memberMap = executeMemberMap.get(0);
						String sender = String.valueOf(memberMap.get("id"));

						JSONObject messageJson=new JSONObject();
						Random r=new Random();
						int index = r.nextInt(chatList.size()); //取随机数
						messageJson.put("content", chatList.get(index).getContent());
						messageJson.put("sender",sender);
						messageJson.put("receiver", memberId);
						messageJson.put("modeType", "robot");
						messageJson.put("msgType", "1");
						messageJson.put("serviceName", "");
						messageJson.put("id", Integer.parseInt(goodsId));
						messageJson.put("sessionKey", "");
						apiSocketController.sendToUser(messageJson.toJSONString());
						count++;
						
						existMemberMap.put(memberId, memberId);
					}
	        		System.out.println("robotMsgFirst执行结束...");
	    		}	
				RedisUtils.releaseDistributedLock("lockKey_robotMsg", "robotMsg");
			}
		} catch (Exception e) {
			e.printStackTrace();
			RedisUtils.releaseDistributedLock("lockKey_robotMsg", "robotMsg");
			return  baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
    	return baseResult.getSuccMap("First推送成功数量："+count);
    }
    
    
    

//  @Scheduled(cron = "0 */15 8-23 * * ? ") // 间隔10分钟执行
  @RequestMapping("/api/robotMsg")
  @ResponseBody
  public  Map<String, Object>  robotMsg() {
	  Integer count=0;
  	try {
  		boolean lock = RedisUtils.tryGetDistributedLock("lockKey_robotMsg", "robotMsg", 60000);
			if(lock){
				String param = paramService.getParam("job_RobotMsgTaskTask");
	    		if("true".equals(param)){
	    			System.out.println("robotMsg执行开始...");
	    			
	    			Calendar calendar1 = Calendar.getInstance();
		    		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
		    		calendar1.add(Calendar.DATE, 0);
		    		String createTime = sdf1.format(calendar1.getTime());
	    			
	    			String  executeSql=" select * from ey_session_info where 1=1"
	    					+ " and create_time > '${createTime}' "
	    					+ " and is_read='${isRead}' "
	    					+ " and mode_type ='${modeType}' "
	    					+ "	and sender in (	select id from ey_member where source_id is not null )"
	    					+ " and content not in ( select content from ey_robot_chat where type='3' )";
	    			
					executeSql=executeSql.replace("${modeType}", "robot");
					executeSql=executeSql.replace("${createTime}",createTime);
					executeSql=executeSql.replace("${isRead}", "1"); //对方已读
					List<Map> executeSessionMap = commonMapperCust.executeSql(executeSql);
	    			for(Map session:executeSessionMap){
	    				String sessionKey=String.valueOf(session.get("session_key"));
	    				String sender=String.valueOf(session.get("sender"));
	    				String receiver=String.valueOf(session.get("receiver"));
	    				String goodsId=String.valueOf(session.get("goods_id"));
	    				
	    				//查询robot发送消息的次数
	    				EyMessageInfoExample exampleMessage = new EyMessageInfoExample();
						com.taotao.pojo.EyMessageInfoExample.Criteria criteriaMessage = exampleMessage.createCriteria();
						criteriaMessage.andSessionKeyEqualTo(sessionKey);
						criteriaMessage.andSenderEqualTo(Integer.parseInt(sender));
						criteriaMessage.andModeTypeEqualTo("robot");
						List<EyMessageInfo> messageList = eyMessageInfoMapper.selectByExample(exampleMessage);
						Integer c=messageList.size();
						String type="";
						String pCategoryId="";
						if(c==3){  //发送次数，
							type="3"; //结束语
						}else if(c<3){
							type="2";    
							EyGoods goods = eyGoodsMapper.selectByPrimaryKey(Integer.parseInt(goodsId));
		    				Integer categoryId = goods.getCategoryId();
		    				EyCategory category = eyCategoryMapper.selectByPrimaryKey(categoryId);
		    				pCategoryId= String.valueOf(category.getParentId());
						}else{ //大于3句 不发送
							continue;
						}
	    				
	    				List<EyRobotChat> chatList=eyChatMapperCust.selectChatContent(sessionKey,sender,goodsId,type,pCategoryId);
	    				if(chatList==null || chatList.size()==0){
	    					continue;
	    				}
						JSONObject messageJson=new JSONObject();
						Random r=new Random();
						int index = r.nextInt(chatList.size()); //取随机数
						messageJson.put("content", chatList.get(index).getContent());
						messageJson.put("sender", sender);
						messageJson.put("receiver", receiver);
						messageJson.put("modeType", "robot");
						messageJson.put("msgType", "1");
						messageJson.put("serviceName", "");
						messageJson.put("id", goodsId);
						messageJson.put("sessionKey", "");
						apiSocketController.sendToUser(messageJson.toJSONString());
						count++;
	    			}
	    			
	        		System.out.println("robotMsg执行结束...");
	    		}	
				RedisUtils.releaseDistributedLock("lockKey_robotMsg", "robotMsg");
			}
		} catch (Exception e) {
			e.printStackTrace();
			RedisUtils.releaseDistributedLock("lockKey_robotMsg", "robotMsg");
			return  baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
    	return baseResult.getSuccMap("Chat推送成功数量："+count);
  }
    
}